<?php
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

// 检查管理员权限
if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => '您没有权限访问此信息']);
    exit;
}

$userId = intval($_GET['id'] ?? 0);

if ($userId <= 0) {
    echo json_encode(['success' => false, 'message' => '用户ID无效']);
    exit;
}

$db = getDB();

// 获取用户信息
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();

if (!$user) {
    echo json_encode(['success' => false, 'message' => '用户不存在']);
    exit;
}

// 处理图片URL
if ($user['wechat_qr']) {
    $user['wechat_qr_url'] = UPLOAD_URL . 'qrcodes/' . $user['wechat_qr'];
}

if ($user['alipay_qr']) {
    $user['alipay_qr_url'] = UPLOAD_URL . 'qrcodes/' . $user['alipay_qr'];
}

// 获取审批人信息（如果有）
if ($user['approved_by']) {
    $stmt = $db->prepare("SELECT username FROM users WHERE id = ?");
    $stmt->execute([$user['approved_by']]);
    $approver = $stmt->fetch();
    $user['approver_name'] = $approver ? $approver['username'] : '未知';
} else {
    $user['approver_name'] = null;
}

// 获取用户订单统计
$stmt = $db->prepare("SELECT 
    COUNT(*) as total,
    COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending,
    COUNT(CASE WHEN status = 'settled' THEN 1 END) as settled,
    COUNT(CASE WHEN status = 'refunded' THEN 1 END) as refunded
FROM orders WHERE user_id = ?");
$stmt->execute([$userId]);
$user['order_stats'] = $stmt->fetch();

echo json_encode(['success' => true, 'data' => $user]);
?>